package com.file.parser;

import com.file.bo.ResponseData;
import com.file.bo.mail.HNNX;
import com.file.bo.mail.HNNXTran;
import com.file.constant.ErrorCode;
import com.file.util.JsonUtils;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 丰巢-海南农信的pdf解析类
 * @author anyspa
 * @date 2023-09-25
 */
@Slf4j
public class HNNXPdfParser extends BasePdfParser{

    public ResponseData<String> parseHNNXPdfToJson(String daId, String filePath) {
        log.info("parseJSPdfToJson started, daId:{}", daId);
        String json = null;

        try {
            HNNX hnnx = parseHNNXPdf(filePath);
            json = JsonUtils.convertObjectToJson(hnnx);
        } catch (Exception e) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseHNNXPdfToJson failed", e);
            return new ResponseData<String>(json, ErrorCode.FILE_PARSE_EXCEPTION.getCode(), ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
        }

        log.info("parseHNNXPdfToJson completed, daId:{}", daId);
        return new ResponseData<String>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }

    public HNNX parseHNNXPdf(String filePath) {
        List<HNNXTran> hnnxTrans = parseTrans(filePath);

        HNNX hnnx = parseHNNXHeader(filePath);

        hnnx.setHnnxTrans(hnnxTrans);

        return hnnx;
    }

    public HNNX parseHNNXHeader(String filePath) {
        HNNX hnnx = new HNNX();
        String pdfHeaderText = parsePdfHeaderText(filePath);

        String currency = pdfHeaderText.substring(pdfHeaderText.indexOf("币种：") + 3, pdfHeaderText.indexOf("账号：")).replaceAll(" ", "").trim(); //NOSONAR
        String accountNo = pdfHeaderText.substring(pdfHeaderText.indexOf("账号：") + 3, pdfHeaderText.indexOf("户名：")).replaceAll(" ", "").trim();  //NOSONAR
        String accountName = pdfHeaderText.substring(pdfHeaderText.indexOf("户名：") + 3, pdfHeaderText.indexOf("起止日期：")).replaceAll(" ", "").trim(); //NOSONAR
        String transDetailPeriod = pdfHeaderText.substring(pdfHeaderText.indexOf("起止日期：") + 5, pdfHeaderText.indexOf("序号 交易日期")).replaceAll(" ", "").trim();
        String generationTime = pdfHeaderText.substring(pdfHeaderText.indexOf("生成日期：") + 5, pdfHeaderText.indexOf("当前页：")).trim();
        hnnx.setCurrency(currency);
        hnnx.setAccountNo(accountNo);
        hnnx.setAccountName(accountName);
        hnnx.setTransDetailPeriod(transDetailPeriod);
        hnnx.setGenerationTime(generationTime);
        return hnnx;
    }

    public List<HNNXTran> parseTrans(String filePath) {
        List<HNNXTran> hnnxTrans = new ArrayList<>();

        String transText = getPdfTextByStripper(filePath);
        if (Strings.isNullOrEmpty(transText)) {
            return hnnxTrans;
        }

        List<List<String>> tranFieldsList = parseTransTextToTranFieldsList2(transText);

        // 序号
        String id = "";
        // 交易日期
        String tranDate = "";
        // 收支类型
        String revenueExpenditureType = "";
        // 摘要
        String summary = "";
        // 交易金额
        String tranAmt = "";
        // 账户余额
        String balance = "";
        // 对方户名
        String counterPartyAccountName = "";
        // 对方户名换行时会出现在记录的前面一行
        int counterPartyAccountNameNumber = 0;
        // 对方账户
        String paymentReceiptAccount = "";

        // 每行的记录是否读取完成
        Boolean rowResult = false;
        for (int i = 0; i < tranFieldsList.size(); i++) {
            List<String> strings = tranFieldsList.get(i);
            // 下一行的数据
            List<String> nextStrings = new ArrayList<>();
            if (i < tranFieldsList.size() - 1) {
                nextStrings = tranFieldsList.get(i + 1);
            }
            if (StringUtils.isBlank(strings.get(0)) || strings.get(0).contains("海南农商银行")  || strings.get(0).contains("币种") || strings.get(0).contains("序号") || strings.get(0).contains("生成日期") || strings.get(0).contains("JYLS") || strings.get(0).contains("累计发生额")) {
                continue;
            }
            log.info(strings.toString());

            String[] contents = strings.get(0).split(" ");
            if (contents.length == 7 || contents.length == 6) {

                id = contents[0];
                tranDate = contents[1];
                revenueExpenditureType = contents[2];
                summary = contents[3];
                tranAmt = contents[4];
                String balanceStr = contents[5];
                counterPartyAccountName = balanceStr.replaceAll("\\d+(\\.\\d+)", "");
                if (StringUtils.equals(balanceStr, counterPartyAccountName)) {
                    // 账户余额为整数时
                    counterPartyAccountName = balanceStr.replaceAll("\\d", "");
                }
                if (StringUtils.isBlank(counterPartyAccountName) || StringUtils.equals("0", counterPartyAccountName) || StringUtils.equals(balanceStr, counterPartyAccountName)) {
                    balance = balanceStr;
                    counterPartyAccountName = "";
                } else {
                    balance = balanceStr.replace(counterPartyAccountName, "");
                }
                if (contents.length == 7) {
                    paymentReceiptAccount = contents[6];
                }
                //这一行完成解析
                if (nextStrings.get(0).split(" ")[0].matches("\\d+") || nextStrings.get(0).contains("生成日期") || nextStrings.get(0).contains("累计发生额")) {
                    rowResult = true;
                }
            } else if (contents.length == 5) {
                id = contents[0];
                tranDate = contents[1];
                revenueExpenditureType = contents[2];
                tranAmt = contents[3];
                balance = contents[4];
                rowResult = true;
            } else {
                if (counterPartyAccountNameNumber < 2) {
                    counterPartyAccountNameNumber += 1;
                    counterPartyAccountName += contents[0];
                } else {
                    paymentReceiptAccount += contents[0];
                }

                if (nextStrings.get(0).split(" ")[0].matches("\\d+")) {
                    rowResult = true;
                }
            }

            if (rowResult && StringUtils.isNotBlank(id)) {
                HNNXTran hnnxTran = new HNNXTran();
                hnnxTran.setId(id);
                hnnxTran.setTranDate(tranDate);
                hnnxTran.setRevenueExpenditureType(revenueExpenditureType);
                hnnxTran.setSummary(summary);
                hnnxTran.setTranAmt(tranAmt);
                hnnxTran.setBalance(balance);
                hnnxTran.setCounterPartyAccountName(counterPartyAccountName);
                hnnxTran.setPaymentReceiptAccount(paymentReceiptAccount);
                hnnxTrans.add(hnnxTran);

                id = "";
                tranDate = "";
                revenueExpenditureType = "";
                summary = "";
                tranAmt = "";
                balance = "";
                counterPartyAccountName = "";
                paymentReceiptAccount = "";
                counterPartyAccountNameNumber = 0;
                rowResult = false;
            }

        }

        return hnnxTrans;
    }

    public List<List<String>> parseTransTextToTranFieldsList2(String transText) {
        // 这个List每个元素代表一条记录的文本字符串
        List<String> tranTextList = Splitter.on(System.getProperty("line.separator", "\n")).splitToList(transText);
        List<List<String>> tranFieldsList = new ArrayList<List<String>>();

        for (int i = 0; i < tranTextList.size() - 1; i++) {
            // 每一个wechatTranFieldList代表一条记录的所有字段，一个List一条记录
            List<String> wechatTranFields = new ArrayList<>();
            wechatTranFields.add(tranTextList.get(i));
            Collections.addAll(tranFieldsList, wechatTranFields);
        }

        return tranFieldsList;
    }

    public static void main(String[] args) {
        HNNXPdfParser pdfParser = new HNNXPdfParser();

        HNNX hnnx = pdfParser.parseHNNXPdf("D:\\data\\file\\beehive-hnnx\\1dd8e4acfc8d48e0b83f2e7845aba979_20231109113358_qz.pdf");
        System.out.println(JsonUtils.convertObjectToJson(hnnx));

    }

}
